﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace MapViewer
{
	public partial class MainPage : PhoneApplicationPage
	{
		// Constructor
		public MainPage()
		{
			InitializeComponent();
		}

		private void Button_Click(object sender, RoutedEventArgs e)
		{
			if (fileName.Text.Length == 0)
			{
				MessageBox.Show("Veuillez indiquer une URL.");
				return;
			}
			Model.RecentItem item = new Model.UrlRecentItem() { Url = fileName.Text };
			goButton.IsEnabled = false;
			LoadItemAsync(item);
		}

		private void LoadItemAsync(Model.RecentItem item)
		{
			// LoadPane.Visibility = System.Windows.Visibility.Visible;
			// (Resources["LoadingAnimation"] as System.Windows.Media.Animation.Storyboard).Begin();
			System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();
			worker.DoWork += delegate
			{
				LoadItem(item);
			};
			worker.RunWorkerAsync();
		}

		private void LoadItem(Model.RecentItem item)
		{
			Action postAction = delegate
			{
				// LoadPane.Visibility = System.Windows.Visibility.Hidden;
				// (Resources["LoadingAnimation"] as System.Windows.Media.Animation.Storyboard).Stop();
				goButton.IsEnabled = true;
			};
			object[] attributes = item.GetType().GetCustomAttributes(typeof(Loaders.LoaderTypeAttribute), false);
			if (attributes.Length == 1)
			{
				Loaders.ILoader loader = (attributes[0] as Loaders.LoaderTypeAttribute).Instance;
				loader.Load(delegate(NamedBinaryTag.TagFile target)
				{
					Dispatcher.BeginInvoke(new Func(delegate
					{
						(Resources["SourceFile"] as NamedBinaryTag.TagFile).Swap(target);
						// fileName.Text = item.Title;
						// UpdateRecent(item);
						postAction();
					}));
				}, item);
			}
			else
			{
				Dispatcher.BeginInvoke(new Action(delegate
				{
					MessageBox.Show("Unable to load selected data.", "Error", MessageBoxButton.OK); 
					postAction();
				}));
			}
		}

		internal delegate void Func();
	}
}